import datetime
import re

from flask import session, request, url_for, redirect, current_app, g, jsonify, render_template

from log_analysis import user_login, db
from log_analysis.models import User, AccessLog, ErrorLog, Site, Remind, Duty, Param, UrlRecord
from . import admin_blu


@admin_blu.route("/", methods=["GET", "POST"])
def admin():
    """
    默认首页登录页
    """
    if request.method == "POST":
        data = request.form
        username = data.get("username")
        password = data.get("password")

        if not all([password, username]):
            return render_template("admin/login.html", status="false", message="参数不全!")

        user = None
        try:
            user = User.query.filter(User.user_name == username).first()
        except Exception as e:
            current_app.logger.error(e)
        if not user:
            return render_template("admin/login.html", status="false", message="账号不存在!")

        if not user.check_passowrd(password):
            return render_template("admin/login.html", status="false", message="密码错误!")

        session["user_id"] = user.user_id
        session["user_name"] = user.user_name
        session["is_admin"] = user.is_admin

        return redirect(url_for("admin.index"))
    else:
        return render_template("admin/login.html", status="true", message="成功!")


@admin_blu.route("/login", methods=["GET", "POST"])
def login():
    """
    用户登录页面显示以及登录:
    get:
    1.如果用户已经登陆，直接跳转到后台首页
    post:
    1.接收参数用户名称和密码
    2.通过用户名称找到密码，校验密码是否正确，以及参数的完整性
    3.校验通过后需要保存用户登陆状态
    4.并且跳转到后台首页
    """
    if request.method == "POST":
        data = request.form
        username = data.get("username")
        password = data.get("password")

        if not all([password, username]):
            return render_template("admin/login.html", status="false", message="参数不全!")

        user = None
        try:
            user = User.query.filter(User.user_name == username).first()
        except Exception as e:
            current_app.logger.error(e)
        if not user:
            return render_template("admin/login.html", status="false", message="账号不存在!")

        if not user.check_passowrd(password):
            return render_template("admin/login.html", status="false", message="密码错误!")

        session["user_id"] = user.user_id
        session["user_name"] = user.user_name
        session["is_admin"] = user.is_admin

        return redirect(url_for("admin.index"))

    user_id = session.get("user_id", None)
    is_admin = session.get("is_admin", False)
    if user_id and is_admin:
        return redirect(url_for("admin.index"))
    else:
        return render_template("admin/login.html", status="true", message="成功!")


@admin_blu.route("/index", methods=["GET", "POST"])
@user_login
def index():
    """
    用户登录后显示首页
    """
    if request.method == "GET":
        user = g.user
        if not user:
            return redirect(url_for("admin.login"))
        else:
            data = {"user": user.to_dict()}
            return render_template("admin/index.html", data=data, status="true", message="成功!")


@admin_blu.route("/logout", methods=["GET", "POST"])
def logout():
    """
    退出登陆
    """
    session.pop("user_id", None)
    session.pop("user_name", None)
    session.pop("is_admin", None)

    return redirect(url_for("admin.login"))


@admin_blu.route("/user_edit", methods=["GET", "POST"])
def user_edit():
    """
    用户编辑
    """
    page = request.args.get("page", 1)
    keywords = request.args.get("keywords", "")

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    user_list = []
    current_page = 1
    total_page = 1

    filters = []
    if keywords:
        filters.append(User.user_name.contains(keywords))

    try:
        paginate = User.query.filter(*filters) \
            .order_by(User.user_id.asc()) \
            .paginate(page, 20, False)

        user_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    if user_list:
        user_dict_list = []
        for user in user_list:
            user_dict_list.append(user.to_dict())

        data = {"total_page": total_page,
                "current_page": current_page,
                "user_list": user_dict_list,
                "keywords": keywords
                }
        return render_template("admin/user_edit.html", data=data, status="true", message="成功!")
    else:
        data = {"total_page": total_page,
                "current_page": current_page,
                "keywords": keywords
                }
        return render_template("admin/user_edit.html", data=data, status="false", message="未查询到数据!")


@admin_blu.route("/user_add", methods=["GET", "POST"])
def user_add():
    """
    用户添加
    """
    if request.method == "POST":

        # is_admin = session.get("is_admin", False)
        # if is_admin:
        data = request.form
        user_name = data.get("user_name")
        nick_name = data.get("nick_name")
        password = data.get("password")
        is_admin = data.get("is_admin")
        phone = data.get("phone")
        email = data.get("email")

        if not all([user_name, nick_name, password, phone]):
            return jsonify(status="false", message="参数不全!")

        # 初始化站点模型，并设置相关数据
        user = User()
        user.user_name = user_name
        user.nick_name = nick_name
        user.password = password

        if is_admin == '1':
            user.is_admin = True
        else:
            user.is_admin = False

        if re.match(r'^1(3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8[0-9]|9[0-9])\d{8}$', phone):
            user.phone = phone
        else:
            return jsonify(status="false", message="手机号码有误!")

        if email:
            if re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}$', email):
                user.email = email
            else:
                return jsonify(status="false", message="邮箱地址有误!")
        else:
            user.email = ""

        # 保存到数据库
        try:
            db.session.add(user)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(status="false", message="添加失败!")
        return jsonify(status="true", message="添加成功!")
    # else:
    #     return jsonify(status="false", message="用户权限不足!")
    else:
        return render_template("admin/user_add.html", status="true", message="成功!")


@admin_blu.route("/user_modify", methods=["GET", "POST"])
def user_modify():
    """
    用户修改
    """
    if request.method == "GET":
        user_id = request.args.get("user_id")
        if not user_id:
            return jsonify(status="false", message="参数有误!")

        # 通过id查询用户数据
        user = None
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)
        if not user:
            return jsonify(status="false", message="未查询到数据!")
        data = {"user": user.to_dict()}
        return render_template("admin/user_modify.html", data=data, status="true", message="成功!")

    # is_admin = session.get("is_admin", False)
    # if is_admin:
    data = request.form
    user_id = data.get("user_id")
    user_name = data.get("user_name")
    nick_name = data.get("nick_name")
    password = data.get("password")
    is_admin = data.get("is_admin")
    phone = data.get("phone")
    email = data.get("email")

    # 判断数据是否有值
    if not all([user_id, user_name, phone]):
        return jsonify(status="false", message="参数不全!")

    user = None
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
    if not user:
        return jsonify(status="false", message="未查询到数据!")

    # 设置相关数据
    user.user_name = user_name
    user.nick_name = nick_name

    if password:
        user.password = password

    if is_admin == '1':
        user.is_admin = True
    else:
        user.is_admin = False

    if re.match(r'^1(3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8[0-9]|9[0-9])\d{8}$', phone):
        user.phone = phone
    else:
        return jsonify(status="false", message="手机号码有误!")

    if email:
        if re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}$', email):
            user.email = email
        else:
            return jsonify(status="false", message="邮箱地址有误!")
    else:
        user.email = ""

    # 保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(status="false", message="修改失败!")
    return jsonify(status="true", message="修改成功!")
    # else:
    #     return jsonify(status="false", message="用户权限不足!")


@admin_blu.route("/user_delete", methods=["GET", "POST"])
def user_delete():
    """
    用户删除
    """
    # 获取查询字符串参数
    if request.method == "GET":
        user_id = request.args.get("user_id")
        if not user_id:
            return jsonify(status="false", message="参数有误!")
        # 通过id查询反馈内容
        user = None
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

        if not user:
            return jsonify(status="false", message="未查询到数据!")
        data = {"user": user.to_dict()}
        return render_template("admin/user_delete.html", data=data, status="true", message="成功!")

    # is_admin = session.get("is_admin", False)
    # if is_admin:
    data = request.form
    user_id = data.get("user_id")

    # 判断数据是否有值
    if not user_id:
        return jsonify(status="false", message="参数有误!")

    user = None
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
    if not user:
        return jsonify(status="false", message="未查询到数据!")

    try:
        db.session.delete(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(status="false", message="删除失败!")
    return jsonify(status="true", message="删除成功!")
    # else:
    #     return jsonify(status="false", message="用户权限不足!")


@admin_blu.route("/log_overview", methods=["GET", "POST"])
def log_overview():
    """
    日志概览
    """
    keywords = request.args.get("keywords", "lbcwx.lingxiu.top.log")
    log_name_list = ["lbcwx.lingxiu.top.log", "lbcwx.lingxiu.top.error.log"]
    if not keywords or keywords not in log_name_list:
        keywords = "lbcwx.lingxiu.top.log"
    log_name = keywords

    cur_time = datetime.datetime.now().strftime("%Y-%m-%d")
    temp_time = request.args.get("temp_time", cur_time)
    # 指定日期前一天的日期字符串
    temp_time = (datetime.datetime.strptime(temp_time, '%Y-%m-%d') - datetime.timedelta(days=1)).strftime("%Y-%m-%d")

    temp_num = request.args.get("temp_num", 0.5)
    temp_num = float(temp_num)

    param = None
    try:
        param = Param.query.filter(Param.log_name == log_name).first()
    except Exception as e:
        current_app.logger.error(e)
    if param:
        pv_count = param.pv_count
        uv_count = param.uv_count
        iv_count = param.iv_count
        max_second_requests = param.max_second_requests
        peak_time = param.peak_time
        avg_second_requests = param.avg_second_requests

        if temp_num == 1.0:
            pv_data = param.pv_data_hour
        else:
            pv_data = param.pv_data_half
        # print(pv_data)
        uv_data = param.uv_data
        # print(uv_data)
        # print(type(uv_data))

        # 字符串还原成列表
        pv_data = eval(pv_data)
        uv_data = eval(uv_data)

        records = None
        try:
            records = UrlRecord.query.filter(UrlRecord.log_name == log_name).order_by(UrlRecord.pv_count.desc()).limit(
                10).all()
        except Exception as e:
            current_app.logger.error(e)
        records_list = []
        for record in records:
            record_list = [record.url, record.pv_count, record.percent, record.peak_count, record.peak_time]
            records_list.append(record_list)
        # print(records_list)

        # hours_time, hours_data, minutes_time, minutes_data = get_chart_data(log_name)
        # method_dict, method_names, method_values = get_method_data()
        # status_dict, status_names, status_values = get_status_data()

        data = {"log_name": log_name,
                "temp_time": temp_time,
                "pv_count": pv_count,
                "uv_count": uv_count,
                "iv_count": iv_count,
                "max_second_requests": max_second_requests,
                "peak_time": peak_time,
                "avg_second_requests": avg_second_requests,

                "pv_data": pv_data,
                "uv_data": uv_data,
                "records_list": records_list,

                # "hours_time": hours_time,
                # "hours_data": hours_data,
                # "minutes_time": minutes_time,
                # "minutes_data": minutes_data,
                }
        # print(data)
        return render_template("admin/log_overview.html", data=data, status="true", message="成功!")
    else:
        data = None
        return render_template("admin/log_overview.html", data=data, status="false", message="未查询到数据!")


@admin_blu.route("/log_details", methods=["GET", "POST"])
def log_details():
    """
    日志详情
    """
    page = request.args.get("page", 1)
    keywords = request.args.get("keywords", "")
    log_name = request.args.get("log_name", "lbcwx.lingxiu.top.log")

    # temp_time = '2020-04-16'  # 日期字符串
    # cur_time = datetime.datetime.strptime(temp_time, '%Y-%m-%d')  # 字符串转日期格式
    cur_time = datetime.datetime.now()
    start_time = (cur_time - datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
    end_time = cur_time.strftime("%Y-%m-%d 00:00:00")
    # print(cur_time, start_time, end_time)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    log_list = []
    current_page = 1
    total_page = 1

    if "error" in log_name:
        filters = [ErrorLog.date_time.between(start_time, end_time)]
        if keywords:
            filters.append(ErrorLog.url.contains(keywords))

        try:
            paginate = ErrorLog.query.filter(*filters) \
                .order_by(ErrorLog.date_time.desc()) \
                .paginate(page, 15, False)

            log_list = paginate.items
            current_page = paginate.page
            total_page = paginate.pages
        except Exception as e:
            current_app.logger.error(e)
    else:
        filters = [AccessLog.date_time.between(start_time, end_time)]
        if keywords:
            filters.append(AccessLog.url.contains(keywords))

        try:
            paginate = AccessLog.query.filter(*filters) \
                .order_by(AccessLog.date_time.desc()) \
                .paginate(page, 15, False)

            log_list = paginate.items
            current_page = paginate.page
            total_page = paginate.pages
        except Exception as e:
            current_app.logger.error(e)

    if log_list:
        log_dict_list = []
        for log in log_list:
            log_dict_list.append(log.to_dict())

        data = {"total_page": total_page,
                "current_page": current_page,
                "log_list": log_dict_list,
                "keywords": keywords,
                "log_name": log_name
                }
        return render_template("admin/log_details.html", data=data, status="true", message="成功!")
    else:
        data = {"total_page": total_page,
                "current_page": current_page,
                "keywords": keywords,
                "log_name": log_name
                }
        return render_template("admin/log_details.html", data=data, status="false", message="未查询到数据!")


@admin_blu.route("/site_edit", methods=["GET", "POST"])
def site_edit():
    """
    站点编辑
    """
    # 获取查询字符串参数
    page = request.args.get("page", 1)
    keywords = request.args.get("keywords", "")

    # 分页显示站点列表数据
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    site_list = []
    current_page = 1
    total_page = 1

    filters = []
    if keywords:
        filters.append(Site.host.contains(keywords))

    try:
        paginate = Site.query.filter(*filters) \
            .order_by(Site.site_id.asc()) \
            .paginate(page, 10, False)

        site_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    if site_list:
        site_dict_list = []
        for site in site_list:
            site_dict_list.append(site.to_dict())

        data = {"total_page": total_page,
                "current_page": current_page,
                "site_list": site_dict_list,
                "keywords": keywords
                }
        return render_template("admin/site_edit.html", data=data, status="true", message="成功!")
    else:
        data = {"total_page": total_page,
                "current_page": current_page,
                "keywords": keywords
                }
        return render_template("admin/site_edit.html", data=data, status="false", message="未查询到数据!")


@admin_blu.route("/site_add", methods=["GET", "POST"])
def site_add():
    """
    站点添加
    """
    if request.method == "POST":

        data = request.form
        site_name = data.get("site_name")
        host = data.get("host")
        access_log = data.get("access_log")
        error_log = data.get("error_log")
        link = data.get("link")

        if not [site_name, host]:
            return jsonify(status="false", message="参数不全!")

        # 初始化站点模型，并设置相关数据
        site = Site()
        site.site_name = site_name
        site.host = host
        site.access_log = access_log
        site.error_log = error_log

        # 正则匹配链接网址
        if link:
            if re.match(
                    r"(http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*,]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)|([a-zA-Z]+.\w+\.+[a-zA-Z0-9\/_]+)",
                    link):
                if 'http' in link:
                    site.link = link
                else:
                    site.link = 'http://' + link
            else:
                return jsonify(status="false", message="链接网址有误!")
        else:
            site.link = ""

        # 保存到数据库
        try:
            db.session.add(site)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(status="false", message="添加失败!")
        return jsonify(status="true", message="添加成功!")
    else:
        return render_template("admin/site_add.html", status="true", message="成功!")


@admin_blu.route('/site_modify', methods=["GET", "POST"])
def site_modify():
    """
    站点修改
    """
    if request.method == "GET":
        site_id = request.args.get("site_id")
        if not site_id:
            return jsonify(status="false", message="参数有误!")
        # 通过id查询站点数据
        site = None
        try:
            site = Site.query.get(site_id)
        except Exception as e:
            current_app.logger.error(e)

        if not site:
            return jsonify(status="false", message="未查询到数据!")
        data = {"site": site.to_dict()}
        return render_template("admin/site_modify.html", data=data, status="true", message="成功!")

    data = request.form
    site_id = data.get("site_id")
    site_name = data.get("site_name")
    host = data.get("host")
    access_log = data.get("access_log")
    error_log = data.get("error_log")
    link = data.get("link")

    # 判断数据是否有值
    if not all([site_id, site_name, host]):
        return jsonify(status="false", message="参数不全!")

    site = None
    try:
        site = Site.query.get(site_id)
    except Exception as e:
        current_app.logger.error(e)
    if not site:
        return jsonify(status="false", message="未查询到数据!")

    # 设置站点相关数据
    site.site_name = site_name
    site.host = host
    site.access_log = access_log
    site.error_log = error_log

    # 正则匹配链接网址
    if link:
        if re.match(
                r"(http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*,]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)|([a-zA-Z]+.\w+\.+[a-zA-Z0-9\/_]+)",
                link):
            if 'http' in link:
                site.link = link
            else:
                site.link = 'http://' + link
        else:
            return jsonify(status="false", message="链接网址有误!")
    else:
        site.link = ""

    # 保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(status="false", message="修改失败!")
    return jsonify(status="true", message="修改成功!")


@admin_blu.route("/site_delete", methods=["GET", "POST"])
def site_delete():
    """
    站点删除
    """
    # 获取查询字符串参数
    if request.method == "GET":
        site_id = request.args.get("site_id")
        if not site_id:
            return jsonify(status="false", message="参数有误!")
        # 通过id查询新站点数据
        site = None
        try:
            site = Site.query.get(site_id)
        except Exception as e:
            current_app.logger.error(e)

        if not site:
            return jsonify(status="false", message="未查询到数据!")
        data = {"site": site.to_dict()}
        return render_template("admin/site_delete.html", data=data, status="true", message="成功!")

    data = request.form
    site_id = data.get("site_id")

    # 判断数据是否有值
    if not site_id:
        return jsonify(status="false", message="参数有误!")

    site = None
    try:
        site = Site.query.get(site_id)
    except Exception as e:
        current_app.logger.error(e)
    if not site:
        return jsonify(status="false", message="未查询到数据!")

    try:
        db.session.delete(site)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(status="false", message="删除失败!")
    return jsonify(status="true", message="删除成功!")


@admin_blu.route("/error_remind", methods=["GET", "POST"])
def error_remind():
    """
    报错提醒
    """
    page = request.args.get("page", 1)
    keywords = request.args.get("keywords", "")

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    remind_list = []
    current_page = 1
    total_page = 1

    filters = []
    if keywords:
        filters.append(Remind.host.contains(keywords))

    try:
        paginate = Remind.query.filter(*filters) \
            .order_by(Remind.date_time.desc()) \
            .paginate(page, 10, False)

        remind_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    if remind_list:
        remind_dict_list = []
        for remind in remind_list:
            remind_dict_list.append(remind.to_dict())

        data = {"total_page": total_page,
                "current_page": current_page,
                "remind_list": remind_dict_list,
                "keywords": keywords
                }
        return render_template("admin/error_remind.html", data=data, status="true", message="成功!")
    else:
        data = {"total_page": total_page,
                "current_page": current_page,
                "keywords": keywords
                }
        return render_template("admin/error_remind.html", data=data, status="false", message="未查询到数据!")


@admin_blu.route("/remind_modify", methods=["GET", "POST"])
def remind_modify():
    """
    修改状态
    """
    if request.method == "GET":
        remind_id = request.args.get("remind_id")
        if not remind_id:
            return jsonify(status="false", message="参数有误!")
        # 通过id查询提醒数据
        remind = None
        try:
            remind = Remind.query.get(remind_id)
        except Exception as e:
            current_app.logger.error(e)

        if not remind:
            return jsonify(status="false", message="未查询到数据!")
        data = {"remind": remind.to_dict()}
        return render_template("admin/remind_modify.html", data=data, status="true", message="成功!")

    data = request.form
    remind_id = data.get("remind_id")
    site_name = data.get("site_name")
    date_time = data.get("date_time")
    host = data.get("host")
    url = data.get("url")
    message = data.get("message")
    remind_state = data.get("remind_state")

    # 判断数据是否有值
    if not all([remind_id, site_name, date_time, host, url, message]):
        return jsonify(status="false", message="参数不全!")

    remind = None
    try:
        remind = Remind.query.get(remind_id)
    except Exception as e:
        current_app.logger.error(e)
    if not remind:
        return jsonify(status="false", message="未查询到数据!")

    # 设置相关数据
    remind.site_name = site_name
    remind.date_time = date_time
    remind.host = host
    remind.url = url
    remind.message = message
    if remind_state == '1':
        remind.remind_state = True
    else:
        remind.remind_state = False

    # 保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(status="false", message="修改失败!")
    return jsonify(status="true", message="修改成功!")


@admin_blu.route("/remind_delete", methods=["GET", "POST"])
def remind_delete():
    """
    提醒删除
    """
    # 获取查询字符串参数
    if request.method == "GET":
        remind_id = request.args.get("remind_id")
        if not remind_id:
            return jsonify(status="false", message="参数有误!")
        # 通过id查询提醒内容
        remind = None
        try:
            remind = Remind.query.get(remind_id)
        except Exception as e:
            current_app.logger.error(e)

        if not remind:
            return jsonify(status="false", message="未查询到数据!")
        data = {"remind": remind.to_dict()}
        return render_template("admin/remind_delete.html", data=data, status="true", message="成功!")

    data = request.form
    remind_id = data.get("remind_id")

    # 判断数据是否有值
    if not remind_id:
        return jsonify(status="false", message="参数有误!")

    remind = None
    try:
        remind = Remind.query.get(remind_id)
    except Exception as e:
        current_app.logger.error(e)
    if not remind:
        return jsonify(status="false", message="未查询到数据!")

    try:
        db.session.delete(remind)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(status="false", message="删除失败!")
    return jsonify(status="true", message="删除成功!")


@admin_blu.route("/param_set", methods=["GET", "POST"])
def param_set():
    """
    参数设置
    """
    # 获取查询字符串参数
    page = request.args.get("page", 1)
    keywords = request.args.get("keywords", "")

    # 分页显示参数列表数据
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    param_list = []
    current_page = 1
    total_page = 1

    # 仅显示错误日志参数
    filters = [Param.log_name.contains("error")]

    if keywords:
        filters.append(Param.log_name.contains(keywords))

    try:
        paginate = Param.query.filter(*filters) \
            .order_by(Param.param_id.asc()) \
            .paginate(page, 10, False)

        param_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    if param_list:
        param_dict_list = []
        for param in param_list:
            param_dict_list.append(param.to_dict())

        data = {"total_page": total_page,
                "current_page": current_page,
                "param_list": param_dict_list,
                "keywords": keywords
                }
        return render_template("admin/param_set.html", data=data, status="true", message="成功!")
    else:
        data = {"total_page": total_page,
                "current_page": current_page,
                "keywords": keywords
                }
        return render_template("admin/param_set.html", data=data, status="false", message="未查询到数据!")


@admin_blu.route('/param_modify', methods=["GET", "POST"])
def param_modify():
    """
    参数修改
    """
    if request.method == "GET":
        param_id = request.args.get("param_id")
        if not param_id:
            return jsonify(status="false", message="参数有误!")
        # 通过id查询参数数据
        param = None
        try:
            param = Param.query.get(param_id)
        except Exception as e:
            current_app.logger.error(e)

        if not param:
            return jsonify(status="false", message="未查询到数据!")
        data = {"param": param.to_dict()}
        return render_template("admin/param_modify.html", data=data, status="true", message="成功!")

    data = request.form
    param_id = data.get("param_id")
    error_count = data.get("error_count")
    error_time = data.get("error_time")
    remind_time = data.get("remind_time")

    # 判断数据是否有值
    if not all([param_id, error_count, error_time, remind_time]):
        return jsonify(status="false", message="参数不全!")

    param = None
    try:
        param = Param.query.get(param_id)
    except Exception as e:
        current_app.logger.error(e)
    if not param:
        return jsonify(status="false", message="未查询到数据!")

    # 设置相关数据
    param.error_count = error_count
    param.error_time = error_time
    param.remind_time = remind_time

    # 保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(status="false", message="修改失败!")
    return jsonify(status="true", message="修改成功!")


@admin_blu.route("/param_delete", methods=["GET", "POST"])
def param_delete():
    """
    参数删除
    """
    # 获取查询字符串参数
    if request.method == "GET":
        param_id = request.args.get("param_id")
        if not param_id:
            return jsonify(status="false", message="参数有误!")
        # 通过id查询新参数数据
        param = None
        try:
            param = Param.query.get(param_id)
        except Exception as e:
            current_app.logger.error(e)

        if not param:
            return jsonify(status="false", message="未查询到数据!")
        data = {"param": param.to_dict()}
        return render_template("admin/param_delete.html", data=data, status="true", message="成功!")

    data = request.form
    param_id = data.get("param_id")

    # 判断数据是否有值
    if not param_id:
        return jsonify(status="false", message="参数有误!")

    param = None
    try:
        param = Param.query.get(param_id)
    except Exception as e:
        current_app.logger.error(e)
    if not param:
        return jsonify(status="false", message="未查询到数据!")

    try:
        db.session.delete(param)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(status="false", message="删除失败!")
    return jsonify(status="true", message="删除成功!")


@admin_blu.route("/duty_calendar", methods=["GET", "POST"])
def duty_calendar():
    """
    值班日历
    """
    # 获取查询字符串参数
    page = request.args.get("page", 1)
    keywords = request.args.get("keywords", "")

    # 分页显示值班列表数据
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    duty_list = []
    current_page = 1
    total_page = 1

    filters = []
    if keywords:
        filters.append(Duty.duty_date.contains(keywords))

    try:
        paginate = Duty.query.filter(*filters) \
            .order_by(Duty.duty_date.desc()) \
            .paginate(page, 10, False)

        duty_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    if duty_list:
        duty_dict_list = []
        for duty in duty_list:
            duty_dict_list.append(duty.to_dict())

        data = {"total_page": total_page,
                "current_page": current_page,
                "duty_list": duty_dict_list,
                "keywords": keywords
                }
        return render_template("admin/duty_calendar.html", data=data, status="true", message="成功!")
    else:
        data = {"total_page": total_page,
                "current_page": current_page,
                "keywords": keywords
                }
        return render_template("admin/duty_calendar.html", data=data, status="false", message="未查询到数据!")


@admin_blu.route("/duty_add", methods=["GET", "POST"])
def duty_add():
    """
    值班添加
    """
    if request.method == "POST":

        data = request.form
        duty_date = data.get("duty_date")
        duty_name = data.get("duty_name")

        if not [duty_date, duty_name]:
            return jsonify(status="false", message="参数不全!")

        user = None
        try:
            user = User.query.filter(User.nick_name == duty_name).first()
        except Exception as e:
            current_app.logger.error(e)

        if not user:
            return jsonify(status="false", message="值班人员不存在!")
        else:
            phone = user.phone
            user_id = user.user_id

        # 初始化值班模型，并设置相关数据
        duty = Duty()
        duty.duty_date = duty_date
        duty.duty_name = duty_name
        duty.phone = phone
        duty.user_id = user_id

        # 保存到数据库
        try:
            db.session.add(duty)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(status="false", message="添加失败!")
        return jsonify(status="true", message="添加成功!")
    else:
        return render_template("admin/duty_add.html", status="true", message="成功!")


@admin_blu.route('/duty_modify', methods=["GET", "POST"])
def duty_modify():
    """
    值班修改
    """
    if request.method == "GET":
        duty_id = request.args.get("duty_id")
        if not duty_id:
            return jsonify(status="false", message="参数有误!")
        # 通过id查询值班数据
        duty = None
        try:
            duty = Duty.query.get(duty_id)
        except Exception as e:
            current_app.logger.error(e)

        if not duty:
            return jsonify(status="false", message="未查询到数据!")
        data = {"duty": duty.to_dict()}
        return render_template("admin/duty_modify.html", data=data, status="true", message="成功!")

    data = request.form
    duty_id = data.get("duty_id")
    duty_date = data.get("duty_date")
    duty_name = data.get("duty_name")

    # 判断数据是否有值
    if not all([duty_id, duty_date, duty_name]):
        return jsonify(status="false", message="参数不全!")

    user = None
    try:
        user = User.query.filter(User.nick_name == duty_name).first()
    except Exception as e:
        current_app.logger.error(e)

    if not user:
        return jsonify(status="false", message="值班人员不存在!")
    else:
        phone = user.phone
        user_id = user.user_id

    duty = None
    try:
        duty = Duty.query.get(duty_id)
    except Exception as e:
        current_app.logger.error(e)
    if not duty:
        return jsonify(status="false", message="未查询到数据!")

    # 设置相关数据
    duty.duty_date = duty_date
    duty.duty_name = duty_name
    duty.phone = phone
    duty.user_id = user_id

    # 保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(status="false", message="修改失败!")
    return jsonify(status="true", message="修改成功!")


@admin_blu.route("/duty_delete", methods=["GET", "POST"])
def duty_delete():
    """
    值班删除
    """
    # 获取查询字符串参数
    if request.method == "GET":
        duty_id = request.args.get("duty_id")
        if not duty_id:
            return jsonify(status="false", message="参数有误!")
        # 通过id查询新站点数据
        duty = None
        try:
            duty = Duty.query.get(duty_id)
        except Exception as e:
            current_app.logger.error(e)

        if not duty:
            return jsonify(status="false", message="未查询到数据!")
        data = {"duty": duty.to_dict()}
        return render_template("admin/duty_delete.html", data=data, status="true", message="成功!")

    data = request.form
    duty_id = data.get("duty_id")

    # 判断数据是否有值
    if not duty_id:
        return jsonify(status="false", message="参数有误!")

    duty = None
    try:
        duty = Duty.query.get(duty_id)
    except Exception as e:
        current_app.logger.error(e)
    if not duty:
        return jsonify(status="false", message="未查询到数据!")

    try:
        db.session.delete(duty)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(status="false", message="删除失败!")
    return jsonify(status="true", message="删除成功!")
